package com.rental.ai.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.Arrays;


@Tag(name = "AI模块")
@RestController
@RequestMapping("/ai")
public class AiController {

    private final Generation generation;

    @Value("${ai.api.key}")
    private String appKey;

    @Autowired
    public AiController(Generation generation) {
        this.generation = generation;
    }

    // 字符串回复
    @Operation(summary = "AI对话")
    @PostMapping("/send")
    public Mono<String> aiTalk(@RequestBody String question, HttpServletResponse response) throws NoApiKeyException, InputRequiredException {
        // 构建消息对象
        Message message = Message.builder().role(Role.USER.getValue()).content(question).build();

        // 构建通义千问参数对象
        GenerationParam param = GenerationParam.builder()
                .model(Generation.Models.QWEN_PLUS)
                .messages(Arrays.asList(message))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .apiKey(appKey)
                .build();

        // 执行文本生成操作，并流式返回结果
        Flux<GenerationResult> result = Flux.from(generation.streamCall(param));
        return result
                .map(m -> m.getOutput().getChoices().get(0).getMessage().getContent())
                .reduce((a, b) -> b) // 只保留最后一个结果
                .doOnError(e -> {
                    // 错误处理
                    String errorMessage = "400: has mistake " + e.getMessage();
                    try {
                        response.setContentType("text/plain");
                        response.setCharacterEncoding("UTF-8");
                        response.getOutputStream().print(errorMessage);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                });
    }

    //文件回复

//    @PostMapping("/send")
//    public Flux<ServerSentEvent<String>> aiTalk(@RequestBody String question, HttpServletResponse response) throws NoApiKeyException, InputRequiredException {
//        // 构建消息对象
//        Message message = Message.builder().role(Role.USER.getValue()).content(question).build();
//
//        // 构建通义千问参数对象
//        GenerationParam param = GenerationParam.builder()
//                .model(Generation.Models.
//                QWEN_PLUS)
//                .messages(Arrays.asList(message))
//                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
//                .topP(0.8)
//                .apiKey(appKey)
//                .build();
//
//        // 执行文本生成操作，并流式返回结果
//        Flowable<GenerationResult> result = generation.streamCall(param);
//        return Flux.from(result)
//                .map(m -> m.getOutput().getChoices().get(0).getMessage().getContent())
//                .collectList() // 收集所有结果到一个列表
//                .flatMapMany(list -> {
//                    if (list.isEmpty()) {
//                        return Flux.empty();
//                    }
//                    String finalResult = list.get(list.size() - 1); // 获取最终结果
//                    return Flux.just(ServerSentEvent.<String>builder().data(finalResult).build());
//                })
//                .publishOn(Schedulers.boundedElastic())
//                .doOnError(e -> {
//                    // 错误处理
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("code", "400");
//                    map.put("message", "has mistake " + e.getMessage());
//                    try {
//                        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
//                        response.setCharacterEncoding("UTF-8");
//                        response.getOutputStream().print(JsonUtils.toJson(map));
//                    } catch (IOException ex) {
//                        ex.printStackTrace();
//                    }
//                });
//    }


}
